<template>
	<view class="user-management-container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<uni-easyinput
				v-model="searchKeyword"
				placeholder="搜索用户名、邮箱或手机号"
				:styles="inputStyles"
				prefixIcon="search"
				@input="handleSearch"
			></uni-easyinput>
		</view>

		<!-- 用户统计 -->
		<view class="user-stats">
			<view class="stat-card">
				<text class="stat-number">{{ totalUsers }}</text>
				<text class="stat-label">总用户数</text>
			</view>
			<view class="stat-card">
				<text class="stat-number">{{ adminUsers }}</text>
				<text class="stat-label">管理员</text>
			</view>
			<view class="stat-card">
				<text class="stat-number">{{ normalUsers }}</text>
				<text class="stat-label">普通用户</text>
			</view>
		</view>

		<!-- 用户列表 -->
		<view class="user-list">
			<view class="list-header">
				<text class="header-title">用户列表</text>
				<view class="filter-buttons">
					<button 
						class="filter-btn" 
						:class="{ active: currentFilter === 'all' }"
						@click="setFilter('all')"
					>
						全部
					</button>
					<button 
						class="filter-btn" 
						:class="{ active: currentFilter === 'admin' }"
						@click="setFilter('admin')"
					>
						管理员
					</button>
					<button 
						class="filter-btn" 
						:class="{ active: currentFilter === 'user' }"
						@click="setFilter('user')"
					>
						普通用户
					</button>
				</view>
			</view>

			<view class="user-cards">
				<view 
					v-for="user in filteredUsers" 
					:key="user.id" 
					class="user-card"
					@click="showUserDetail(user)"
				>
					<view class="user-info">
						<image :src="user.avatar" class="user-avatar" mode="aspectFill"></image>
						<view class="user-details">
							<view class="user-name-row">
								<text class="user-name">{{ user.username }}</text>
								<view class="user-role" :class="user.role">
									<text class="role-text">{{ getRoleText(user.role) }}</text>
								</view>
							</view>
							<text class="user-email">{{ user.email }}</text>
							<text class="user-phone">{{ user.phone || '未设置手机号' }}</text>
							<text class="register-time">注册时间：{{ formatTime(user.registerTime) }}</text>
						</view>
					</view>
					<view class="user-actions">
						<button 
							v-if="user.role !== 'admin' || user.id !== userStore.userInfo.id"
							class="action-btn edit-btn" 
							@click.stop="editUser(user)"
						>
							编辑
						</button>
						<button 
							v-if="user.id !== userStore.userInfo.id"
							class="action-btn delete-btn" 
							@click.stop="deleteUser(user)"
						>
							删除
						</button>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="filteredUsers.length === 0" class="empty-state">
				<uni-icons type="person" size="80" color="#cccccc"></uni-icons>
				<text class="empty-text">暂无用户数据</text>
			</view>
		</view>

		<!-- 用户详情弹窗 -->
		<uni-popup ref="userDetailPopup" type="bottom">
			<view class="user-detail-popup">
				<view class="popup-header">
					<text class="popup-title">用户详情</text>
					<button class="close-btn" @click="closeUserDetail">
						<uni-icons type="close" size="20" color="#666666"></uni-icons>
					</button>
				</view>
				<view class="popup-content" v-if="selectedUser">
					<view class="detail-item">
						<text class="detail-label">用户ID：</text>
						<text class="detail-value">{{ selectedUser.id }}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">用户名：</text>
						<text class="detail-value">{{ selectedUser.username }}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">角色：</text>
						<text class="detail-value">{{ getRoleText(selectedUser.role) }}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">邮箱：</text>
						<text class="detail-value">{{ selectedUser.email }}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">手机号：</text>
						<text class="detail-value">{{ selectedUser.phone || '未设置' }}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">注册时间：</text>
						<text class="detail-value">{{ formatTime(selectedUser.registerTime) }}</text>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 编辑用户弹窗 -->
		<uni-popup ref="editUserPopup" type="center">
			<view class="edit-user-popup">
				<view class="popup-header">
					<text class="popup-title">编辑用户</text>
				</view>
				<view class="popup-content" v-if="editingUser">
					<view class="form-item">
						<text class="form-label">用户名：</text>
						<uni-easyinput
							v-model="editingUser.username"
							placeholder="请输入用户名"
							:styles="inputStyles"
						></uni-easyinput>
					</view>
					<view class="form-item">
						<text class="form-label">邮箱：</text>
						<uni-easyinput
							v-model="editingUser.email"
							placeholder="请输入邮箱"
							:styles="inputStyles"
						></uni-easyinput>
					</view>
					<view class="form-item">
						<text class="form-label">手机号：</text>
						<uni-easyinput
							v-model="editingUser.phone"
							placeholder="请输入手机号"
							:styles="inputStyles"
						></uni-easyinput>
					</view>
					<view class="form-item">
						<text class="form-label">角色：</text>
						<picker 
							:value="roleIndex" 
							:range="roleOptions" 
							range-key="text"
							@change="onRoleChange"
						>
							<view class="picker-input">
								{{ roleOptions[roleIndex].text }}
								<uni-icons type="bottom" size="14" color="#999999"></uni-icons>
							</view>
						</picker>
					</view>
				</view>
				<view class="popup-actions">
					<button class="cancel-btn" @click="cancelEdit">取消</button>
					<button class="confirm-btn" @click="confirmEdit">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { useUserStore } from '@/stores/user.js'

export default {
	data() {
		return {
			searchKeyword: '',
			currentFilter: 'all',
			selectedUser: null,
			editingUser: null,
			roleIndex: 0,
			roleOptions: [
				{ value: 'user', text: '普通用户' },
				{ value: 'admin', text: '管理员' }
			],
			inputStyles: {
				color: '#333333',
				backgroundColor: '#f8f8f8',
				borderColor: '#e0e0e0'
			}
		}
	},
	setup() {
		const userStore = useUserStore()
		return {
			userStore
		}
	},
	onLoad() {
		this.checkAdminPermission()
		this.loadUserData()
	},
	computed: {
		totalUsers() {
			return this.userStore.users.length
		},
		adminUsers() {
			return this.userStore.users.filter(user => user.role === 'admin').length
		},
		normalUsers() {
			return this.userStore.users.filter(user => user.role === 'user').length
		},
		filteredUsers() {
			let users = this.userStore.users

			// 角色过滤
			if (this.currentFilter !== 'all') {
				users = users.filter(user => user.role === this.currentFilter)
			}

			// 搜索过滤
			if (this.searchKeyword.trim()) {
				const keyword = this.searchKeyword.toLowerCase()
				users = users.filter(user => 
					user.username.toLowerCase().includes(keyword) ||
					user.email.toLowerCase().includes(keyword) ||
					(user.phone && user.phone.includes(keyword))
				)
			}

			return users
		}
	},
	methods: {
		// 检查管理员权限
		checkAdminPermission() {
			this.userStore.initUserData()
			
			if (!this.userStore.isAdmin) {
				uni.showModal({
					title: '权限不足',
					content: '您没有管理员权限，无法访问此页面',
					showCancel: false,
					success: () => {
						uni.navigateBack()
					}
				})
				return false
			}
			return true
		},

		// 加载用户数据
		loadUserData() {
			this.userStore.initUserData()
		},

		// 搜索处理
		handleSearch() {
			// 搜索逻辑在computed中处理
		},

		// 设置过滤器
		setFilter(filter) {
			this.currentFilter = filter
		},

		// 获取角色文本
		getRoleText(role) {
			const roleMap = {
				'admin': '管理员',
				'user': '普通用户',
				'guest': '游客'
			}
			return roleMap[role] || '未知'
		},

		// 格式化时间
		formatTime(timeString) {
			if (!timeString) return '未知'
			const date = new Date(timeString)
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
		},

		// 显示用户详情
		showUserDetail(user) {
			this.selectedUser = user
			this.$refs.userDetailPopup.open()
		},

		// 关闭用户详情
		closeUserDetail() {
			this.$refs.userDetailPopup.close()
			this.selectedUser = null
		},

		// 编辑用户
		editUser(user) {
			this.editingUser = { ...user }
			this.roleIndex = this.roleOptions.findIndex(option => option.value === user.role)
			this.$refs.editUserPopup.open()
		},

		// 角色选择变化
		onRoleChange(e) {
			this.roleIndex = e.detail.value
			this.editingUser.role = this.roleOptions[this.roleIndex].value
		},

		// 取消编辑
		cancelEdit() {
			this.$refs.editUserPopup.close()
			this.editingUser = null
		},

		// 确认编辑
		confirmEdit() {
			if (!this.editingUser.username.trim()) {
				uni.showToast({
					title: '请输入用户名',
					icon: 'none'
				})
				return
			}

			if (!this.editingUser.email.trim()) {
				uni.showToast({
					title: '请输入邮箱',
					icon: 'none'
				})
				return
			}

			// 检查用户名是否重复（排除自己）
			const existingUser = this.userStore.users.find(u => 
				u.username === this.editingUser.username && u.id !== this.editingUser.id
			)
			if (existingUser) {
				uni.showToast({
					title: '用户名已存在',
					icon: 'none'
				})
				return
			}

			// 检查邮箱是否重复（排除自己）
			const existingEmail = this.userStore.users.find(u => 
				u.email === this.editingUser.email && u.id !== this.editingUser.id
			)
			if (existingEmail) {
				uni.showToast({
					title: '邮箱已被使用',
					icon: 'none'
				})
				return
			}

			// 更新用户信息
			const userIndex = this.userStore.users.findIndex(u => u.id === this.editingUser.id)
			if (userIndex !== -1) {
				this.userStore.users[userIndex] = { ...this.editingUser }
				this.userStore.saveUsersToStorage()
				
				uni.showToast({
					title: '用户信息更新成功',
					icon: 'success'
				})
				
				this.cancelEdit()
			}
		},

		// 删除用户
		deleteUser(user) {
			uni.showModal({
				title: '删除用户',
				content: `确定要删除用户"${user.username}"吗？此操作不可恢复！`,
				success: (res) => {
					if (res.confirm) {
						const userIndex = this.userStore.users.findIndex(u => u.id === user.id)
						if (userIndex !== -1) {
							this.userStore.users.splice(userIndex, 1)
							this.userStore.saveUsersToStorage()
							
							uni.showToast({
								title: '用户删除成功',
								icon: 'success'
							})
						}
					}
				}
			})
		}
	}
}
</script>

<style scoped>
.user-management-container {
	background: #f5f5f5;
	min-height: 100vh;
	padding: 30rpx;
}

.search-bar {
	margin-bottom: 30rpx;
}

.user-stats {
	display: flex;
	gap: 20rpx;
	margin-bottom: 30rpx;
}

.stat-card {
	flex: 1;
	background: white;
	padding: 30rpx;
	border-radius: 20rpx;
	text-align: center;
}

.stat-number {
	display: block;
	font-size: 48rpx;
	font-weight: bold;
	color: #ff6b35;
	margin-bottom: 10rpx;
}

.stat-label {
	font-size: 26rpx;
	color: #666666;
}

.user-list {
	background: white;
	border-radius: 20rpx;
	overflow: hidden;
}

.list-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.header-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.filter-buttons {
	display: flex;
	gap: 10rpx;
}

.filter-btn {
	padding: 10rpx 20rpx;
	font-size: 24rpx;
	border: 1rpx solid #e0e0e0;
	border-radius: 20rpx;
	background: white;
	color: #666666;
}

.filter-btn.active {
	background: #ff6b35;
	color: white;
	border-color: #ff6b35;
}

.user-cards {
	max-height: 1000rpx;
	overflow-y: auto;
}

.user-card {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.user-card:last-child {
	border-bottom: none;
}

.user-info {
	display: flex;
	align-items: center;
	flex: 1;
}

.user-avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50rpx;
	margin-right: 30rpx;
}

.user-details {
	flex: 1;
}

.user-name-row {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
}

.user-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-right: 20rpx;
}

.user-role {
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
	font-size: 20rpx;
}

.user-role.admin {
	background: #ff6b35;
	color: white;
}

.user-role.user {
	background: #4CAF50;
	color: white;
}

.role-text {
	font-size: 20rpx;
}

.user-email, .user-phone, .register-time {
	display: block;
	font-size: 26rpx;
	color: #666666;
	margin-bottom: 5rpx;
}

.user-actions {
	display: flex;
	gap: 10rpx;
}

.action-btn {
	padding: 10rpx 20rpx;
	font-size: 24rpx;
	border-radius: 15rpx;
	border: none;
}

.edit-btn {
	background: #4CAF50;
	color: white;
}

.delete-btn {
	background: #f44336;
	color: white;
}

.empty-state {
	text-align: center;
	padding: 100rpx 30rpx;
}

.empty-text {
	display: block;
	margin-top: 30rpx;
	font-size: 28rpx;
	color: #999999;
}

/* 弹窗样式 */
.user-detail-popup, .edit-user-popup {
	background: white;
	border-radius: 20rpx 20rpx 0 0;
	max-height: 80vh;
	overflow: hidden;
}

.edit-user-popup {
	border-radius: 20rpx;
	width: 600rpx;
	max-height: 70vh;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.close-btn {
	background: none;
	border: none;
	padding: 10rpx;
}

.popup-content {
	padding: 30rpx;
	max-height: 500rpx;
	overflow-y: auto;
}

.detail-item {
	display: flex;
	margin-bottom: 20rpx;
}

.detail-label {
	width: 150rpx;
	font-size: 28rpx;
	color: #666666;
}

.detail-value {
	flex: 1;
	font-size: 28rpx;
	color: #333333;
}

.form-item {
	margin-bottom: 30rpx;
}

.form-label {
	display: block;
	font-size: 28rpx;
	color: #333333;
	margin-bottom: 10rpx;
}

.picker-input {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	background: #f8f8f8;
	border: 1rpx solid #e0e0e0;
	border-radius: 10rpx;
	font-size: 28rpx;
	color: #333333;
}

.popup-actions {
	display: flex;
	gap: 20rpx;
	padding: 30rpx;
	border-top: 1rpx solid #f0f0f0;
}

.cancel-btn, .confirm-btn {
	flex: 1;
	height: 80rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
	border: none;
}

.cancel-btn {
	background: #f5f5f5;
	color: #666666;
}

.confirm-btn {
	background: #ff6b35;
	color: white;
}
</style>
